package univ.uchiha.esiag.gon.broadcaster;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import javax.rmi.PortableRemoteObject;

import org.omg.CORBA.ORB;
import org.omg.CORBA.Object;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;

import univ.uchiha.esiag.gon.domaine.local.impl.LocalDomaineManagerImpl;
import univ.uchiha.esiag.gon.domaine.local.impl._LocalDomaineManagerImpl_Tie;
import univ.uchiha.esiag.gon.domaine.remote.RemoteDomaineManager;

public class BroadcasterLocal extends Thread{
	private static ORB orb;
	private LocalDomaineManagerImpl local;
	public BroadcasterLocal(String[] args, LocalDomaineManagerImpl local) {
		orb = ORB.init(args, null);
		this.local = local;
		new Thread(new Runnable() {
			public void run() {
				orb.run();
			}
		}).start();
	}
	public static ORB getORB(){
		return orb;
	}
	@Override
	public void run() {
		try{
			byte[] buf = "Hello".getBytes();
			DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getByName("228.5.6.7"), 8090);
			DatagramSocket socket = new DatagramSocket();
			socket.send(packet);
			socket.close();
			while(true){
				ServerSocket ssocket = new ServerSocket(8091);
				Socket socket1 = ssocket.accept();
				BufferedReader br = new BufferedReader(new InputStreamReader(socket1.getInputStream()));
				String ior = br.readLine();
				Object objRef = orb.string_to_object(ior);
				RemoteDomaineManager rdm = (RemoteDomaineManager) PortableRemoteObject.narrow(objRef, RemoteDomaineManager.class);
				response(rdm);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public void response(RemoteDomaineManager remote){
		try{
			_LocalDomaineManagerImpl_Tie tie = new _LocalDomaineManagerImpl_Tie();
			tie.setTarget(local);
			POA rootPOA = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
			rootPOA.the_POAManager().activate();
			Object objRef = rootPOA.servant_to_reference(tie);
			String ior = orb.object_to_string(objRef);
			remote.register(ior);
			local.setRemoteDomainManager(remote);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
